/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.gui.client;

import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.*;
import com.gwtext.client.widgets.event.*;
import com.gwtext.client.data.*;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.core.*;
import java.util.*;

import nfse.gui.client.data.*;

public class EventStatsGrid extends Panel {

    private HashMap dataMap;

    private HeadsUpTab headsUpTab;

    private GridPanel grid;

    private ToolbarTextItem text;

    private boolean refresh = false;

    public EventStatsGrid(int height, int width) {
        this.setHeight(height);
        this.setWidth(width);
        this.setBorder(true);
    }

    public void buildGrid(HashMap dataMap, HeadsUpTab headsUpTab) {
        this.headsUpTab = headsUpTab;
        this.dataMap = dataMap;
        buildGrid();
    }

    public void buildGrid() {

        RecordDef recordDef = new RecordDef(new FieldDef[] { new StringFieldDef("sensor"), new StringFieldDef("count"),
                new StringFieldDef("oldest"), new StringFieldDef("newest"), });

        grid = new GridPanel();

        Object[][] data = null;
        data = convertRawDataToObjectGrid();
        MemoryProxy proxy = new MemoryProxy(data);

        ArrayReader reader = new ArrayReader(recordDef);
        Store store = new Store(proxy, reader);
        store.load();
        grid.setStore(store);

        ColumnConfig[] columns = new ColumnConfig[] { new ColumnConfig("Sensor", "sensor", 100) {
            {
                setAlign(TextAlign.LEFT);
            }
        }, new ColumnConfig("Count", "count", 60) {
            {
                setAlign(TextAlign.RIGHT);
            }
        }, new ColumnConfig("Oldest", "oldest", 150), new ColumnConfig("Newest", "newest", 150) };

        ColumnModel columnModel = new ColumnModel(columns);

        grid.setColumnModel(columnModel);
        grid.setFrame(true);
        grid.setStripeRows(true);
        grid.setAutoScroll(true);
        grid.setHeight(200);
        grid.setTitle("Event Stats");

        Toolbar tBar = new Toolbar();
        ButtonListenerAdapter listener = new ButtonListenerAdapter() {
            public void onClick(Button button, com.gwtext.client.core.EventObject e) {
                System.out.println("The refresh button was clicked");
                refreshThis();
                // updateFooterTimeStamp();
            }
        };

        ToolbarButton refreshBtn = new ToolbarButton("Refresh", listener);
        tBar.addButton(refreshBtn);
        Date today = new Date();

        // tBar.addText("Last Updated: " + today);
        if (text != null)
            text.removeFromParent();
        text = new ToolbarTextItem("Last Updated: " + today);
        // tBar.addItem(text);
        grid.setBottomToolbar(tBar);

        // Button b1 = new Button("AAHHHH");
        // this.add(b1);

        this.add(grid);
    }

    public void refreshGrid(HashMap dataMap) {
        this.dataMap = dataMap;
        RecordDef recordDef = new RecordDef(new FieldDef[] { new StringFieldDef("sensor"), new StringFieldDef("count"),
                new StringFieldDef("oldest"), new StringFieldDef("newest") });

        Object[][] data = convertRawDataToObjectGrid();
        MemoryProxy proxy = new MemoryProxy(data);

        ArrayReader reader = new ArrayReader(recordDef);
        Store store = new Store(proxy, reader);
        store.load();
        // localG.setStore(store);

        ColumnConfig[] columns = new ColumnConfig[] { new ColumnConfig("Sensor", "sensor", 100) {
            {
                setAlign(TextAlign.LEFT);
            }
        }, new ColumnConfig("Count", "count", 60) {
            {
                setAlign(TextAlign.RIGHT);
            }
        }, new ColumnConfig("Oldest", "oldest", 150), new ColumnConfig("Newest", "newest", 150) };

        ColumnModel columnModel = new ColumnModel(columns);

        // localG.setColumnModel(columnModel);

        grid.reconfigure(store, columnModel);

        // grid.setFrame(true);
        // grid.setStripeRows(true);
        // grid.setAutoScroll(true);
        // grid.setHeight(100);
        // grid.setTitle("Event Stats");

        // Toolbar tBar = new Toolbar();
        // ButtonListenerAdapter listener = new ButtonListenerAdapter() {
        // public void onClick(Button button, com.gwtext.client.core.EventObject
        // e) {
        // System.out.println("The refresh button was clicked");
        // refreshThis();
        // //updateFooterTimeStamp();
        // }
        // };
        //		
        // ToolbarButton refreshBtn = new ToolbarButton("Refresh",listener);
        // tBar.addButton(refreshBtn);
        // Date today = new Date( );
        //        	
        // //tBar.addText("Last Updated: " + today);
        // if (text != null)
        // text.removeFromParent();
        // text = new ToolbarTextItem("Last Updated: " + today);
        // tBar.addItem(text);
        // grid.setBottomToolbar(tBar);

        grid.getBottomToolbar();
        // this.remove(grid);

        // grid = localG;
        // this.insert(0,localG);

        // return grid;

    }

    private void configureGridData(boolean refresh, GridPanel grid) {
        this.grid = grid;
        this.refresh = refresh;

        RecordDef recordDef = new RecordDef(new FieldDef[] { new StringFieldDef("sensor"), new StringFieldDef("count"),
                new StringFieldDef("oldest"), new StringFieldDef("newest"), });

        Object[][] data = convertRawDataToObjectGrid();
        MemoryProxy proxy = new MemoryProxy(data);

        ArrayReader reader = new ArrayReader(recordDef);
        Store store = new Store(proxy, reader);

        ColumnConfig[] columns = new ColumnConfig[] { new ColumnConfig("Sensor", "sensor", 100) {
            {
                setAlign(TextAlign.LEFT);
            }
        }, new ColumnConfig("Count", "count", 60) {
            {
                setAlign(TextAlign.RIGHT);
            }
        }, new ColumnConfig("Oldest", "oldest", 150), new ColumnConfig("Newest", "newest", 150) };

        ColumnModel columnModel = new ColumnModel(columns);

        if (!refresh) {
            grid.setStore(store);
            grid.setColumnModel(columnModel);
        } else {
            grid.reconfigure(store, columnModel);
        }

    }

    public void updateFooterTimeStamp() {
        // if (text != null)
        // text.removeFromParent();

        text.getParent();
        text = new ToolbarTextItem("Last Updated: " + new Date());

        grid.getBottomToolbar().addItem(text);
    }

    private void refreshThis() {
        this.headsUpTab.refreshEventStatsGrid();
    }

    /**
     * This converts the incoming data object a HashMap or an ArrayList into a
     * Object[][]
     */
    private Object[][] convertRawDataToObjectGrid() {
        ArrayList usedTypes = new ArrayList();

        int columns = 4;

        Object[][] displayData = new Object[headsUpTab.getSensorTypesMap().size()][columns];

        int recordCount = 0;

        Iterator it = dataMap.keySet().iterator();
        while (it.hasNext()) {
            EventStats eventStats = (EventStats) dataMap.get((String) it.next());
            SensorTypes st = (SensorTypes) headsUpTab.getSensorTypesMap().get(eventStats.getTypeId());
            if (st != null) {
                usedTypes.add(eventStats.getTypeId());
                String sensorName = st.getTypeName();
                displayData[recordCount][0] = sensorName;
                displayData[recordCount][1] = eventStats.getEventCount();
                displayData[recordCount][2] = eventStats.getOldestEvent();
                displayData[recordCount][3] = eventStats.getNewestEvent();
                recordCount++;
            }
        }

        // Add the sensors that do not have counts
        Iterator it2 = headsUpTab.getSensorTypesMap().keySet().iterator();
        while (it2.hasNext()) {
            String typeId = (String) it2.next();
            if (!usedTypes.contains(typeId)) {
                SensorTypes st = (SensorTypes) headsUpTab.getSensorTypesMap().get(typeId);
                String sensorName = st.getTypeName();
                displayData[recordCount][0] = sensorName;
                displayData[recordCount][1] = "0";
                displayData[recordCount][2] = "0";
                displayData[recordCount][3] = "0";
                recordCount++;
            }
        }

        return displayData;
    }

    private Object[][] getTestData() {
        return new Object[][] {
                new Object[] { "5", new Integer(1000), "2005-12-20 00:00:00.0", "2005-11-14 00:00:00.0" },
                new Object[] { "3", new Integer(500), "2004-10-02 00:00:00.0", "2005-11-07 00:00:00.0" },
                new Object[] { "5", new Integer(1000), "2005-12-20 00:00:00.0", "2005-11-14 00:00:00.0" },
                new Object[] { "3", new Integer(500), "2004-10-02 00:00:00.0", "2005-11-07 00:00:00.0" },
                new Object[] { "5", new Integer(1000), "2005-12-20 00:00:00.0", "2005-11-14 00:00:00.0" },
                new Object[] { "3", new Integer(500), "2004-10-02 00:00:00.0", "2005-11-07 00:00:00.0" } };
    }

    public GridPanel getGrid() {
        return grid;
    }

    public void setGrid(GridPanel grid) {
        this.grid = grid;
    }

}
